package com.yellow.orderservice.controller;

import com.yellow.orderservice.entity.*;
import com.yellow.orderservice.exception.OrderAlreadyGrabbedException;
import com.yellow.orderservice.service.ItemService;
import com.yellow.orderservice.service.OrderService;
import com.yellow.orderservice.service.ReceiverService;
import com.yellow.orderservice.service.SenderService;
import com.yellow.orderservice.utils.CommonUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: hy
 * @create: 2024-02-20
 */
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/order")
@Slf4j
public class OrderController {
    @Resource
    private OrderService orderService;
    @Resource
    private ItemService itemService;

    @Resource
    private SenderService senderService;

    @Resource
    private ReceiverService receiverService;


    /**
     * 通过UserId 查询对应订单
     * @param userId
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/byUserId/{id}")
    public List<Order> selectOrderListByUserId(@PathVariable("id") Integer userId) throws InterruptedException {
        return orderService.selectOrderListByUserId(userId);
    }

    @GetMapping("/getByOrderId/{id}")
    public Order selectByOrderId(@PathVariable("id") Integer orderId){
        return orderService.findByOrderId(orderId);
    }

    @GetMapping("/getCourierNameByOrderId/{id}")
    public String getCourierNameByOrderId(@PathVariable("id") Integer orderId){
        return orderService.getCourierNameByOrderId(orderId);
    }

    /**
     * 查询所有订单
     * @return
     */
    @GetMapping("/allOrders")
    public List<Order> selectAllOrders(){
        return orderService.selectAllOrders();
    }

    /**
     * 根据orderId 查询具体物品
     * @param orderId
     * @return
     */
    @GetMapping("/item/{id}")
    public Item selectItemByOrderId(@PathVariable("id") Long orderId){
        return itemService.selectByOrderId(orderId);
    }

    @PostMapping("/grab/{orderId}")
    public ResponseEntity<?> grabOrder(@PathVariable("orderId") Integer orderId,@RequestBody GrabOrderRequest grabOrderRequest) {
        String courierName = grabOrderRequest.getCourierName();
        try {
            // 尝试抢单
            orderService.grabOrder(orderId, courierName);
            log.info("用户{}抢单成功!", courierName);
            return ResponseEntity.ok().body("{\"message\": \"Grab successful\"}");
        } catch (OrderAlreadyGrabbedException e) {
            // 订单已被抢
            return ResponseEntity.status(HttpStatus.CONFLICT).body(e.getMessage());
        } catch (Exception e) {
            // 其他错误
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    @Transactional
    @PostMapping("/orderNow")
    public ResponseEntity<?> orderNow(@RequestBody Map<String,Object> req){
        Map<String,Object>map = swapAndProcess(req);
        Sender sender = (Sender) map.get("sender");
        Receiver receiver = (Receiver) map.get("receiver");
        Order order = (Order) map.get("order");
        log.info("sender = {}",sender);
        log.info("receiver = {}",receiver);
        log.info("order = {}",order);
        senderService.insertSender(sender);
        receiverService.insertReceiver(receiver);
        orderService.insertOrder(order);

        Long sender_id = sender.getSenderId();
        Long receiver_id = receiver.getReceiverId();
        Long orderId = orderService.countOrders();
        log.info("sender_id:{},receiver_id:{}", sender_id, receiver_id);
        Item item = new Item( itemService.countItems() + 1,
                sender_id, receiver_id,
                orderId,
                (String)map.get("objectName"),
                (Double) map.get("totalWeight"),
                (int)map.get("totalPieces"),
                "https://i0.imgs.ovh/2024/01/17/h8xYj.png");
        log.info("item = {}", item);
        itemService.insertItem(item);
        orderService.insertCustomerOrders(Math.toIntExact(sender_id), Math.toIntExact(orderId), (long) (orderService.countCustomerOrders()+1));
        return ResponseEntity.ok().body("{\"message\": \"insertAll successful\",\"orderId\": "+ orderId +"}");
    }

    @SuppressWarnings("unchecked")
    private Map<String,Object> swapAndProcess(Map<String,Object> req){
        String sendName = ((Map<String,Object>)(req.get("send_wrap"))).get("name").toString();
        String sendPhoneNumber = ((Map<String,Object>)(req.get("send_wrap"))).get("phoneNumber").toString();
        String sendProvince= ((Map<String,Object>)(req.get("send_wrap"))).get("province").toString();
        String sendAddress = ((Map<String,Object>)(req.get("send_wrap"))).get("address").toString();
        String sendCompanyName = ((Map<String,Object>)(req.get("send_wrap"))).get("companyName").toString();

        String receiveName = ((Map<String,Object>)(req.get("receive_wrap"))).get("name").toString();
        String receivePhoneNumber = ((Map<String,Object>)(req.get("receive_wrap"))).get("phoneNumber").toString();
        String receiveProvince= ((Map<String,Object>)(req.get("receive_wrap"))).get("province").toString();
        String receiveAddress = ((Map<String,Object>)(req.get("receive_wrap"))).get("address").toString();
        String receiveCompanyName = ((Map<String,Object>)(req.get("receive_wrap"))).get("companyName").toString();

        String sendWay = (String) req.get("send_way");
        String whenPay = (String) req.get("payway");
        String wishTime = (String) req.get("wish_time");
        String objectName = (String) req.get("object_name");
        double totalWeight = Double.parseDouble(String.valueOf(req.get("total_weight")));
        int totalPieces = (int) req.get("total_pieces");

        Sender sender = new Sender(senderService.countSenders()+1, sendName, sendPhoneNumber, sendProvince, sendAddress, sendCompanyName, sendWay);
        Receiver receiver = new Receiver(receiverService.contReceivers()+1, receiveName, receivePhoneNumber, receiveProvince, receiveAddress, receiveCompanyName, sendWay);
        Order order = new Order(orderService.countOrders() + 1, 0L, "标运", "未派单", CommonUtil.getNowDateTime(), "暂无", "上海仓库", whenPay, CommonUtil.getNowDateTime(), "官方网站", "支付宝", "易碎品", receiveAddress, "暂无", "是", "暂无接单员");
        HashMap<String, Object> wrapper = new HashMap<>();
        wrapper.put("sender",sender);
        wrapper.put("receiver",receiver);
        wrapper.put("payWay",whenPay);
        wrapper.put("wishTime",wishTime);
        wrapper.put("objectName",objectName);
        wrapper.put("totalWeight",totalWeight);
        wrapper.put("totalPieces",totalPieces);
        wrapper.put("order",order);

        return wrapper;
    }


    @PostMapping("/{orderId}/incr-view")
    public void viewOrder(@PathVariable String orderId) {
        orderService.incrementOrderViewCount(orderId);
    }

    @GetMapping("/{orderId}/view-count")
    public int getOrderViewCount(@PathVariable String orderId) {
        return orderService.getOrderViewCount(orderId);
    }


}
